package cn.tedu.config;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/**
 * @author Kiven
 */
public class DateTimeConverter implements Converter<Date> {
    private static final String PATTERN_YYYY_MM_DD = "yyyy年MM月dd日";

    @Override
    public Class supportJavaTypeKey() {
        return Date.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public Date convertToJavaData(CellData cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat(PATTERN_YYYY_MM_DD);
        Date parse = null;
        String formattedDate = null;
        try {
            parse = dateFormat.parse(cellData.getStringValue());
            return parse;
        }catch (Exception e){
            // 有时候excel导入进来是一个数字，比如1900年1月1日是1，1900年1月2日是2，以此类推 2024年03月12日是45632
            //BigDecimal numberValue = cellData.getNumberValue();
            //String s = numberValue.toString();
            //Double doubleValue = Double.parseDouble(s);
            //long l = doubleValue.longValue()-2;
            //System.out.println(doubleValue);
            LocalDate localDate = LocalDate.of(1900, 1, 1).plusDays(cellData.getNumberValue().longValue() - 2);

            // 如果需要，可以将LocalDate格式化为字符串
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy年MM月dd日");
            formattedDate = localDate.format(formatter);
            return  dateFormat.parse(formattedDate);
        }

    }

    @Override
    public CellData convertToExcelData(Date dateTime, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        SimpleDateFormat dateFormat = new SimpleDateFormat(PATTERN_YYYY_MM_DD);
        String dateValue = dateFormat.format(dateTime);
        return new CellData<>(dateValue);
    }
}
